<template>
  <div>
    <el-dialog :title="'文件上传'" :close-on-click-modal="false" :visible.sync="dialogVisible" center width="27%">

      <el-upload
        ref="upload"
        drag
        action="https://daily-project.oss-cn-guangzhou.aliyuncs.com"
        :data="dataObj"
        :auto-upload="false"
        list-type="picture"
        multipl
        :before-upload="beforeUpload"
        :on-success="handleUploadSuccess"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,不建议文件名含有空格</div>
      </el-upload>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpload()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api/system/oss'
export default {
  name: 'OssAddOrUpdate',
  data() {
    return {
      dataObj: {
        policy: '',
        signature: '',
        key: '',
        ossaccessKeyId: '',
        dir: '',
        host: ''
      },
      dialogVisible: false
    }
  },
  methods: {
    init() {
      this.dialogVisible = true
    },
    beforeUpload(file) {
      const _self = this
      return new Promise((resolve, reject) => {
        api.policy().then(response => {
          _self.dataObj.policy = response.data.policy
          _self.dataObj.signature = response.data.signature
          _self.dataObj.ossaccessKeyId = response.data.accessid
          _self.dataObj.key = response.data.dir + '_${filename}'
          _self.dataObj.dir = response.data.dir
          _self.dataObj.host = response.data.host
          resolve(true)
        }).catch(err => {
          reject(false)
        })
      })
    },
    // 确认上传文件
    submitUpload() {
      this.$refs.upload.submit()
    },
    // 文件上传到阿里云oss服务器成功后的回调
    handleUploadSuccess(response, file, fileList) {
      // 1.判断上传的图片列表是否都为success状态
      const successFlag = fileList.every(file => {
        return file.status === 'success'
      })

      if (successFlag) {
        const decodeUrls = fileList.map(file => {
          const url = this.dataObj.host + '/' + this.dataObj.key.replace('${filename}', file.name)
          // console.log("编码后的url", decodeURI(url));
          // console.log("解码后的url", encodeURI(url));
          const decodeUrl = decodeURI(url)
          return decodeUrl
        })
        api.savePolicyImgs(decodeUrls).then(res => [
          this.$message({
            message: res.msg,
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.dialogVisible = false
              this.$emit('refreshDataList')
            }
          })
        ])
      }
    }
  }
}
</script>
<style>

</style>

